package goxpath
import (
"encoding/xml"
"fmt"
"github.com/ChrisTrenkamp/goxpath/internal/execxp"
"github.com/ChrisTrenkamp/goxpath/parser"
"github.com/ChrisTrenkamp/goxpath/tree"
)
type Opts struct {
NS map [string ]string
Funcs map [xml .Name ]tree .Wrap
Vars map [string ]tree .Result
}
type FuncOpts func (*Opts )
type XPathExec struct {
n *parser .Node
}
func Parse (xp string ) (XPathExec , error ) {
n , err := parser .Parse (xp )
return XPathExec {n : n }, err
}
func MustParse (xp string ) XPathExec {
ret , err := Parse (xp )
if err != nil {
panic (err )
}
return ret
}
func (xp XPathExec ) Exec (t tree .Node , opts ...FuncOpts ) (tree .Result , error ) {
o := &Opts {
NS : make (map [string ]string ),
Funcs : make (map [xml .Name ]tree .Wrap ),
Vars : make (map [string ]tree .Result ),
}
for _ , i := range opts {
i (o )
}
return execxp .Exec (xp .n , t , o .NS , o .Funcs , o .Vars )
}
func (xp XPathExec ) ExecBool (t tree .Node , opts ...FuncOpts ) (bool , error ) {
res , err := xp .Exec (t , opts ...)
if err != nil {
return false , err
}
b , ok := res .(tree .IsBool )
if !ok {
return false , fmt .Errorf ("Cannot convert result to a boolean" )
}
return bool (b .Bool ()), nil
}
func (xp XPathExec ) ExecNum (t tree .Node , opts ...FuncOpts ) (float64 , error ) {
res , err := xp .Exec (t , opts ...)
if err != nil {
return 0 , err
}
n , ok := res .(tree .IsNum )
if !ok {
return 0 , fmt .Errorf ("Cannot convert result to a number" )
}
return float64 (n .Num ()), nil
}
func (xp XPathExec ) ExecNode (t tree .Node , opts ...FuncOpts ) (tree .NodeSet , error ) {
res , err := xp .Exec (t , opts ...)
if err != nil {
return nil , err
}
n , ok := res .(tree .NodeSet )
if !ok {
return nil , fmt .Errorf ("Cannot convert result to a node-set" )
}
return n , nil
}
func (xp XPathExec ) MustExec (t tree .Node , opts ...FuncOpts ) tree .Result {
res , err := xp .Exec (t , opts ...)
if err != nil {
panic (err )
}
return res
}
func ParseExec (xpstr string , t tree .Node , opts ...FuncOpts ) (tree .Result , error ) {
xp , err := Parse (xpstr )
if err != nil {
return nil , err
}
return xp .Exec (t , opts ...)
}
The pages are generated with Golds v0.6.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds .